import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:provider/provider.dart';
import 'package:wms/utils/message_box.dart';
import 'package:wms/utils/utils.dart';
import '../system/fontsize_provider.dart';
import '../../utils/rangeInput_formatter.dart';
import '../../services/auth_service.dart';
import '../../services/api_service.dart';
import 'package:http/http.dart' as http;
import 'dart:convert';

class MoveScreen extends StatefulWidget {
  const MoveScreen({super.key});

  @override
  _MoveScreenState createState() => _MoveScreenState();
}

class _MoveScreenState extends State<MoveScreen> with WidgetsBindingObserver {
  // 输入控制器
  final TextEditingController _itemController = TextEditingController();
  final TextEditingController _locationController = TextEditingController();
  final TextEditingController _quantityController = TextEditingController();
  final TextEditingController _destLocController = TextEditingController();
  final TextEditingController _notesController = TextEditingController();

  // 焦点控制器（【修改1：Location和Item设为不可请求焦点】）
  final FocusNode _itemFocusNode = FocusNode(canRequestFocus: false);
  final FocusNode _locationFocusNode = FocusNode(canRequestFocus: false);
  final FocusNode _quantityFocusNode = FocusNode(canRequestFocus: true);
  final FocusNode _destLocFocusNode = FocusNode(canRequestFocus: true);
  final FocusNode _notesFocusNode = FocusNode(canRequestFocus: true);

  // 键盘状态管理（【修改2：移除Location和Item的键盘状态】）
  bool _quantityKeyboardVisible = false;
  bool _destLocKeyboardVisible = false;
  String? _currentFocusField;
  String? packKey;
  String? internalItemNumber;
  double listFontSize = 12;

  // 业务数据（【修改3：修正列表类型，存储列表所需字段】）
  int? currentQuantity;
  late int maxAllowedValue = 99999999;
  late double _fontScale;
  int? warehouseId;
  int itemId = 0;
  Map<String, dynamic>? selectedListItem; // 选中的列表项
  Map<String, String?> validationErrors = {};
  static const double _bottomButtonHeight = 80;
  static const double _listHeight = 200; // 列表固定高度
  List<Map<String, dynamic>> availableSkus = []; // 列表数据（明确类型）

  @override
  void initState() {
    super.initState();
    WidgetsBinding.instance.addObserver(this);

    // 输入监听（保留必要的错误清除）
    _itemController.addListener(() => _clearErrorOnInput('item'));
    _locationController.addListener(() => _clearErrorOnInput('location'));
    _quantityController.addListener(() => _clearErrorOnInput('move quantity'));
    _destLocController.addListener(() => _clearErrorOnInput('dest loc'));
    
    // 焦点监听（【修改4：移除Location和Item的焦点监听】）
    _initFocusListeners();
    // 【修改5：初始化时加载列表数据，移除原Location初始聚焦】
    _initCountData();
  }

  // 初始化焦点监听（仅保留Quantity和DestLoc）
  void _initFocusListeners() {
    _quantityFocusNode.addListener(() {
      _handleFocusChange('quantity', _quantityFocusNode);
    });
    _destLocFocusNode.addListener(() {
      _handleFocusChange('destLoc', _destLocFocusNode);
    });
  }

  // 应用生命周期监听（简化键盘重置逻辑）
  @override
  void didChangeAppLifecycleState(AppLifecycleState state) {
    super.didChangeAppLifecycleState(state);
    if (state == AppLifecycleState.resumed && mounted) {
      _resetAllKeyboards();
    }
  }

  // 焦点变化处理（核心修改：获焦时主动触发键盘，失焦时隐藏）
  void _handleFocusChange(String field, FocusNode node) {
    if (node.hasFocus) {
      if (_currentFocusField != null && _currentFocusField != field) {
        _hideKeyboardForField(_currentFocusField!); // 隐藏前一个输入框键盘
      }
      _setCurrentFocusField(field);
      _showKeyboardForField(field); // 获焦立即弹键盘
    } else if (_currentFocusField == field) {
      _hideKeyboardForField(field);
      _currentFocusField = null;
    }
  }

  // 键盘控制方法（【修改6：优化键盘显示逻辑，增加状态校验】）
  void _setCurrentFocusField(String field) => setState(() => _currentFocusField = field);
  
  // 核心修改：增加字段校验，避免空字段调用键盘
  void _showKeyboard() async {
    if (_currentFocusField == null) return;
    try {
      await SystemChannels.textInput.invokeMethod('TextInput.show');
    } catch (e) {
      print('显示键盘失败: $e');
      await Future.delayed(const Duration(milliseconds: 50));
      await SystemChannels.textInput.invokeMethod('TextInput.show');
    }
  }
  
  Future<void> _hideKeyboard() async {
    try {
      await SystemChannels.textInput.invokeMethod('TextInput.hide');
      await Future.delayed(const Duration(milliseconds: 50));
      await SystemChannels.textInput.invokeMethod('TextInput.hide');
    } catch (e) {
      print('隐藏键盘失败: $e');
      await Future.delayed(const Duration(milliseconds: 100));
      await SystemChannels.textInput.invokeMethod('TextInput.hide');
    }
  }
  
  // 显示键盘（补充状态更新）
  void _showKeyboardForField(String field) {
    if (!mounted) return;
    setState(() {
      if (field == 'quantity') _quantityKeyboardVisible = true;
      if (field == 'destLoc') _destLocKeyboardVisible = true;
    });
    _showKeyboard();
  }
  
  // 隐藏键盘（补充状态更新）
  void _hideKeyboardForField(String field) {
    if (!mounted) return;
    setState(() {
      if (field == 'quantity') _quantityKeyboardVisible = false;
      if (field == 'destLoc') _destLocKeyboardVisible = false;
    });
    _hideKeyboard();
  }
  
  // 切换键盘（仅允许Quantity和DestLoc）
  void _toggleKeyboardForField(String field) {
    if (!['quantity', 'destLoc'].contains(field)) return;
    if (_getKeyboardState(field)) {
      _hideKeyboardForField(field);
      _unfocusField(field);
    } else {
      _focusOnField(field, showKeyboard: true);
    }
  }
  
  // 聚焦方法（核心修改：增加滚动+延迟键盘触发，解决挡住问题）
  void _focusOnField(String field, {required bool showKeyboard}) {
    FocusScope.of(context).unfocus(); // 先取消所有焦点
    if (!mounted) return;

    // 1. 请求目标输入框焦点
    switch (field) {
      case 'quantity':
        FocusScope.of(context).requestFocus(_quantityFocusNode);
        break;
      case 'destLoc':
        FocusScope.of(context).requestFocus(_destLocFocusNode);
        break;
    }

    // 2. 核心：聚焦后自动滚动到输入框（避免被键盘挡住）
    WidgetsBinding.instance.addPostFrameCallback((_) {
      FocusNode? focusNode;
      switch (field) {
        case 'quantity':
          focusNode = _quantityFocusNode;
          break;
        case 'destLoc':
          focusNode = _destLocFocusNode;
          break;
      }

      // 确保输入框在可视区域
      if (focusNode?.context != null) {
        Scrollable.ensureVisible(
          focusNode!.context!,
          alignment: 0.4, // 滚动到屏幕40%高度位置（中间偏上，不被键盘挡）
          duration: const Duration(milliseconds: 200),
          curve: Curves.easeInOut,
        );
      }

      // 3. 延迟触发键盘（等待焦点稳定）
      if (showKeyboard && mounted) {
        Future.delayed(const Duration(milliseconds: 100), () {
          _showKeyboardForField(field);
        });
      } else if (mounted) {
        _hideKeyboardForField(field);
      }
    });
  }
  
  // 取消指定输入框焦点
  void _unfocusField(String field) {
    switch (field) {
      case 'quantity': _quantityFocusNode.unfocus(); break;
      case 'destLoc': _destLocFocusNode.unfocus(); break;
    }
  }
  
  // 获取键盘状态（仅Quantity和DestLoc）
  bool _getKeyboardState(String field) {
    switch (field) {
      case 'quantity': return _quantityKeyboardVisible;
      case 'destLoc': return _destLocKeyboardVisible;
      default: return false;
    }
  }
  
  // 更新键盘状态（仅Quantity和DestLoc）
  void _updateKeyboardState(String field, bool visible) {
    setState(() {
      switch (field) {
        case 'quantity': _quantityKeyboardVisible = visible; break;
        case 'destLoc': _destLocKeyboardVisible = visible; break;
      }
    });
  }
  
  // 重置所有键盘状态
  void _resetAllKeyboards() {
    if (_currentFocusField == null && !_quantityKeyboardVisible && !_destLocKeyboardVisible) {
      return;
    }
    setState(() {
      _quantityKeyboardVisible = false;
      _destLocKeyboardVisible = false;
      _currentFocusField = null;
    });
    FocusScope.of(context).unfocus();
    _hideKeyboard();
  }

  @override
  void dispose() {
    WidgetsBinding.instance.removeObserver(this);
    // 移除焦点监听（仅保留必要的）
    _quantityFocusNode.removeListener(() => _handleFocusChange('quantity', _quantityFocusNode));
    _destLocFocusNode.removeListener(() => _handleFocusChange('destLoc', _destLocFocusNode));
    
    // 释放控制器资源
    _itemController.dispose();
    _locationController.dispose();
    _quantityController.dispose();
    _notesController.dispose();
    _destLocController.dispose();
    
    // 释放焦点资源
    _itemFocusNode.dispose();
    _locationFocusNode.dispose();
    _quantityFocusNode.dispose();
    _destLocFocusNode.dispose();
    _notesFocusNode.dispose();
    
    super.dispose();
  }

  // 【核心新增：初始化列表数据（与CountScreen逻辑一致）】
  void _initCountData() async {
    if (!mounted) return;
    try {
      final cycleResponse = await _getCountTasks();
      print('cycleResponse----$cycleResponse');
      if (cycleResponse['code'] == 2000 && cycleResponse['data'] != null) {
        setState(() {
          // 仅保留列表显示+业务必要字段
          availableSkus = (cycleResponse['data'] as List).map((detail) => {
            'id': detail['id'] ?? 0,
            'itemNumber': detail['item_number'] ?? 'N/A', // 对应Item Number
            'locationNumber': detail['location'] ?? 'N/A', // 对应Location
            'quantity': detail['damaged_quantity'] ?? 0, // 对应Qty
            'packKey': detail['pack_key'] ?? '', // 提交API必要字段
            'internalItemNumber': detail['internal_item_number'] ?? '', // 提交API必要字段
          }).cast<Map<String, dynamic>>().toList();
        });
      }
    } catch (e) {
      MessageBox.showMessageBox(context, 'Items列表加载失败: $e', isError: true);
    }
  }

  // 【核心修改：获取列表数据（原方法改为获取列表，而非单个数量）】
  Future<Map<String,dynamic>> _getCountTasks() async{
    print('warehouseId----$warehouseId');
    // 列表API参数（参考CountScreen，添加operation_type=Move）
    final param = 'page=1&limit=100&operation_type=Move';
    final apiUrl = '${ApiService.baseURL}${ApiService.getMoveOrCountTasks}$param';
    
    final authService = Provider.of<AuthService>(context, listen: false);
    final accessToken = authService.accessToken;
    
    try {
      final response = await http.get(
        Uri.parse(apiUrl),
        headers: {
          'Authorization': 'JWT $accessToken',
          'x-warehouse-id': '$warehouseId',
          'x-timezone': 'America/Los_Angeles',
          'Content-Type':'application/json',
          'X-Client-Type':'app'
        },
      );
      
      if (response.statusCode == 200) {
        String responseBody = utf8.decode(response.bodyBytes);
        return json.decode(responseBody);
      } else if (response.statusCode == 401) {
        AuthService auth = AuthService();
        auth.logout(context);
        throw Exception('Session expired, please login again');
      } else {
        throw Exception('Server error: ${response.statusCode}');
      }
    } catch (e) {
      throw Exception(e);
    }
  }

  // 【核心新增：列表项选中处理（回填输入框数据）】
  void _handleItemListSelection(Map<String, dynamic> item) {
    if (!mounted) return;
    setState(() {
      // 取消选中：清空数据
      if (selectedListItem == item) {
        selectedListItem = null;
        _locationController.clear();
        _itemController.clear();
        _quantityController.clear();
        currentQuantity = null;
        maxAllowedValue = 99999999;
        validationErrors.removeWhere((key, _) => key == 'location' || key == 'item' || key == 'move quantity');
        packKey = null;
        internalItemNumber = null;
      } 
      // 选中项：回填数据
      else {
        selectedListItem = item;
        itemId = item['id'];
        _locationController.text = item['locationNumber'] ?? '';
        _itemController.text = item['itemNumber'] ?? '';
        _quantityController.text = item['quantity'].toString(); // 默认填充当前Qty
        currentQuantity = item['quantity'] ?? 0;
        maxAllowedValue = currentQuantity ?? 0;
        // 存储提交API必要字段
        packKey = item['packKey'] ?? '';
        internalItemNumber = item['internalItemNumber'] ?? '';
        // 选中后自动聚焦到Move Qty（弹键盘）
        _focusOnField('quantity', showKeyboard: true);
      }
    });
  }

  // 错误处理（保留原逻辑）
  void _clearErrorOnInput(String fieldKey) {
    if (validationErrors.containsKey(fieldKey)) {
      setState(() {
        if ((fieldKey == 'item' && _itemController.text.isNotEmpty) ||
            (fieldKey == 'location' && _locationController.text.isNotEmpty) ||
            (fieldKey == 'dest loc' && _destLocController.text.isNotEmpty) ||
            (fieldKey == 'move quantity' && _quantityController.text.isNotEmpty)) {
          validationErrors.remove(fieldKey);
        }
      });
    }
  }

  // 【修改8：提交后更新列表+清空数据】
  void _submitForm() async{
    _resetAllKeyboards();
    bool isValid = true;
    Map<String, String?> errors = {};
    
    try{
      // 表单验证（保留原逻辑）
      if (_itemController.text.isEmpty) {
        errors['item'] = 'Please select from Items list.';
        isValid = false;
      }
      if (_locationController.text.isEmpty) {
        errors['location'] = 'Please select from Items list.';
        isValid = false;
      }
      if (_quantityController.text.isEmpty) {
        errors['move quantity'] = 'Please input move quantity.';
        isValid = false;
      } else if ((int.tryParse(_quantityController.text) ?? 0) > (currentQuantity ?? 0)) {
        errors['move quantity'] = 'Move Qty cannot exceed current Qty ($currentQuantity)';
        isValid = false;
      }
      if (_destLocController.text.isEmpty) {
        errors['dest loc'] = 'Please input dest loc.';
        isValid = false;
      }

      setState(() => validationErrors = errors);

      if (isValid) {
        final responseData = await _callAdjustmentAPI();
        if(responseData['code'] == 2000){
          MessageBox.showMessageBox(context, responseData['msg']);
          
          // 【关键：提交成功后重新加载列表】
          _initCountData();
          
          // 清空所有输入和状态
          setState(() {
            selectedListItem = null;
            _locationController.clear();
            _itemController.clear();
            _quantityController.clear();
            _destLocController.clear();
            _notesController.clear();
            currentQuantity = null;
            maxAllowedValue = 99999999;
          });
          
          _notesFocusNode.unfocus();
          FocusScope.of(context).unfocus();
          await _hideKeyboard();
        }
      }
    } catch(e) {
      MessageBox.showMessageBox(context, e, isError: true);
    }
  }

  // 调用提交API（【修改9：使用列表选中的packKey和internalItemNumber】）
  Future<Map<String,dynamic>> _callAdjustmentAPI() async{
    final apiUrl = ApiService.baseURL + ApiService.moveLocation;
    final authService = Provider.of<AuthService>(context, listen: false);
    final accessToken = authService.accessToken;
    
    if (packKey == null || internalItemNumber == null) {
      throw Exception('Missing item information, please reselect from Items list');
    }
    
    try {
      var requestBody = {
        'warehouse': warehouseId,
        'source_location': _locationController.text.trim(),
        'internal_item_number': internalItemNumber,
        'pack_key': packKey,
        'move_quantity': _quantityController.text.isEmpty ? 0 : int.parse(_quantityController.text.trim()),
        'dest_location': _destLocController.text.trim(),
        'notes': _notesController.text.trim(),
        'cycle_task_id':itemId
      };
      
      final response = await http.post(
        Uri.parse(apiUrl),
        headers: {
          'Authorization': 'JWT $accessToken',
          'x-warehouse-id': '$warehouseId',
          'x-timezone': 'America/Los_Angeles',
          'Content-Type':'application/json',
          'X-Client-Type':'app'
        },
        body: jsonEncode(requestBody),
      );
      
      if(response.statusCode == 200){
        String responseBody = utf8.decode(response.bodyBytes);
        Map<String, dynamic> jsonData = json.decode(responseBody);
        print('apiUrl------$apiUrl');
        print('requestBody------$requestBody');
        print('jsonData------$jsonData');
        if (jsonData['code'] == 2000) {
          return jsonData;
        } else if(jsonData['code'] == 401){
          AuthService auth = AuthService();
          auth.logout(context);
          throw Exception('Session expired, please login again');
        } else {
          throw Exception(jsonData['msg']);
        }
      } else {
        throw Exception('Server error: ${response.statusCode}');
      }
    } catch (e) {
      throw Exception(e.toString());
    }
  }

  // 构建输入框行（保留原布局，适配输入框修改）
  Widget _buildLabelInputRow({
    required String label,
    required bool isRequired,
    required String errorKey,
    String? fieldType,
    Widget? suffixWidget,
  }) {
    final isSmallScreen = MediaQuery.of(context).size.width < 360;
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        SizedBox(
          height: 30,
          child: Row(
            crossAxisAlignment: CrossAxisAlignment.center,
            children: [
              SizedBox(
                width: 120,
                child: Row(
                  children: [
                    Text(
                      label,
                      style: TextStyle(fontWeight: FontWeight.bold, fontSize: 13 * _fontScale),
                    ),
                    if (isRequired)
                      const Text('*', style: TextStyle(color: Colors.red)),
                  ],
                ),
              ),
              const SizedBox(width: 16),
              Expanded(
                child: _buildInputField(fieldType, isSmallScreen),
              ),
              if (suffixWidget != null)
                Padding(
                  padding: const EdgeInsets.only(left: 8),
                  child: suffixWidget,
                ),
            ],
          ),
        ),
        if (validationErrors[errorKey] != null)
          Padding(
            padding: const EdgeInsets.only(left: 136, top: 4),
            child: Text(
              validationErrors[errorKey]!,
              style: TextStyle(color: Colors.red, fontSize: 12 * _fontScale),
            ),
          ),
      ],
    );
  }

  // 【修改10：输入框组件（Location和Item设为只读+无键盘）】
  Widget _buildInputField(String? fieldType, bool isSmallScreen) {
    if (fieldType == null) return Container();
    
    TextEditingController? controller;
    FocusNode? focusNode;
    TextInputType keyboardType = TextInputType.text;
    List<TextInputFormatter>? inputFormatters;
    Function()? onTap;
    Function(String)? onChanged;

    switch (fieldType) {
      case 'location':
        controller = _locationController;
        focusNode = _locationFocusNode;
        onTap = () => _onReadOnlyInputTap(controller!); // 只读输入框点击逻辑
        onChanged = (_) => _clearErrorOnInput('location');
        break;
      case 'item':
        controller = _itemController;
        focusNode = _itemFocusNode;
        onTap = () => _onReadOnlyInputTap(controller!); // 只读输入框点击逻辑
        onChanged = (_) => _clearErrorOnInput('item');
        break;
      case 'quantity':
        controller = _quantityController;
        focusNode = _quantityFocusNode;
        keyboardType = TextInputType.number;
        inputFormatters = [
          FilteringTextInputFormatter.digitsOnly,
          RangeInputFormatter(maxAllowedValue)
        ];
        onTap = () => _onInputTap(controller!, fieldType);
        onChanged = (_) => _clearErrorOnInput('move quantity');
        break;
      case 'destLoc':
        controller = _destLocController;
        focusNode = _destLocFocusNode;
        onTap = () => _onInputTap(controller!, fieldType);
        onChanged = (_) => _clearErrorOnInput('dest loc');
        break;
    }

    return TextField(
      controller: controller,
      focusNode: focusNode,
      keyboardType: keyboardType,
      inputFormatters: inputFormatters,
      readOnly: fieldType == 'location' || fieldType == 'item', // 【关键：Location和Item只读】
      decoration: InputDecoration(
        border: const OutlineInputBorder(),
        contentPadding: const EdgeInsets.symmetric(vertical: 0, horizontal: 10),
        // 【关键：仅Quantity和DestLoc显示键盘图标】
        suffixIcon: ['quantity', 'destLoc'].contains(fieldType)
            ? IconButton(
                icon: Icon(
                  _getKeyboardState(fieldType) ? Icons.keyboard_hide : Icons.keyboard,
                  color: const Color(0xFF008363),
                  size: isSmallScreen ? 18 : 20,
                ),
                onPressed: () => _toggleKeyboardForField(fieldType),
                splashRadius: 20,
                padding: const EdgeInsets.all(4),
                constraints: const BoxConstraints.tightFor(width: 36, height: 36),
              )
            : null,
      ),
      style: TextStyle(fontSize: 13 * _fontScale),
      onTap: onTap,
      onChanged: onChanged,
      onTapOutside: (event) {
        if (['quantity', 'destLoc'].contains(fieldType)) {
          _hideKeyboardForField(fieldType);
          _unfocusField(fieldType);
        }
      },
    );
  }

  // 【新增：只读输入框点击处理（仅选中文本，不聚焦）】
  void _onReadOnlyInputTap(TextEditingController controller) {
    if (controller.text.isNotEmpty) {
      controller.selection = TextSelection(
        baseOffset: 0,
        extentOffset: controller.text.length,
      );
    }
    _resetAllKeyboards(); // 点击只读输入框时收起其他键盘
  }

  // 可编辑输入框点击处理（核心修改：showKeyboard设为true，点击即弹键盘）
  void _onInputTap(TextEditingController controller, String fieldType) {
    if (controller.text.isNotEmpty) {
      controller.selection = TextSelection(
        baseOffset: 0,
        extentOffset: controller.text.length,
      );
    }
    _focusOnField(fieldType, showKeyboard: true); // 原false改为true
  }

  // 【修改11：简化焦点方法（移除Location和Item处理）】
  void _focusOnFieldWithNotes(String field, {required bool showKeyboard}) {
    FocusScope.of(context).unfocus();
    if (mounted) {
      switch (field) {
        case 'quantity':
          FocusScope.of(context).requestFocus(_quantityFocusNode);
          break;
        case 'destLoc':
          FocusScope.of(context).requestFocus(_destLocFocusNode);
          break;
        case 'notes':
          FocusScope.of(context).requestFocus(_notesFocusNode);
          break;
      }
      if (showKeyboard && ['quantity', 'destLoc'].contains(field)) {
        _showKeyboardForField(field);
      } else {
        _hideKeyboard();
        if (['quantity', 'destLoc'].contains(field)) {
          _updateKeyboardState(field, false);
        }
      }
    }
  }

  // 【核心新增：构建Items列表（与CountScreen样式一致）】
  Widget _buildItemsList() {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        // 列表标题
        Text(
          'Move Tasks:',
          style: TextStyle(
            fontWeight: FontWeight.bold,
            fontSize: 13 * _fontScale,
          ),
        ),
        // 列表容器
        Container(
          height: _listHeight,
          decoration: BoxDecoration(
            border: Border.all(color: Colors.grey, width: 1.0),
            borderRadius: BorderRadius.circular(4.0),
          ),
          child: ClipRRect(
            borderRadius: BorderRadius.circular(4.0),
            child: ListView.builder(
              physics: const ClampingScrollPhysics(),
              itemCount: availableSkus.length,
              itemBuilder: (context, index) {
                final skuItem = availableSkus[index];
                final isSelected = selectedListItem == skuItem;
                
                return InkWell(
                  onTap: () => _handleItemListSelection(skuItem),
                  child: Container(
                    margin: const EdgeInsets.symmetric(vertical: 2),
                    decoration: BoxDecoration(
                      border: Border.all(color: const Color.fromARGB(255, 169, 168, 168), width: 0.5),
                      borderRadius: BorderRadius.circular(4.0),
                      color: isSelected ? Colors.green[50] : null,
                    ),
                    padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 12),
                    // 横向布局：3列分别显示3个字段
                    child: Row(
                      mainAxisAlignment: MainAxisAlignment.spaceBetween,
                      children: [
                        // 1. Location
                        Expanded(
                          flex: 1,
                          child: Text(
                            '${skuItem['locationNumber']}',
                            style: TextStyle(
                              fontSize: listFontSize * _fontScale,
                              color: isSelected ? Colors.green : Colors.black87,
                            ),
                          ),
                        ),
                        // 2. Item Number
                        Expanded(
                          flex: 1,
                          child: Text(
                            '${skuItem['itemNumber']}',
                            style: TextStyle(
                              fontSize: listFontSize * _fontScale,
                              color: isSelected ? Colors.green : Colors.black87,
                            ),
                          ),
                        ),
                        // 3. Qty
                        Expanded(
                          flex: 1,
                          child: Text(
                            '${skuItem['quantity']}',
                            style: TextStyle(
                              fontSize: listFontSize * _fontScale,
                              color: isSelected ? Colors.green : Colors.black87,
                            ),
                          ),
                        ),
                      ],
                    ),
                  ),
                );
              },
            ),
          ),
        ),
        const SizedBox(height: 20), // 列表与输入框间距
      ],
    );
  }

  @override
  Widget build(BuildContext context) {
    _fontScale = Provider.of<FontSizeProvider>(context).fontScale;
    final user = Provider.of<AuthService>(context).currentUser;
    warehouseId = user?.warehouse;
    final isSmallScreen = MediaQuery.of(context).size.width < 360;
    final bottomInset = MediaQuery.of(context).viewInsets.bottom; // 获取键盘高度

    return Scaffold(
      appBar: AppBar(
        title: Text('Move', style: TextStyle(fontWeight: FontWeight.bold, fontSize: 18 * _fontScale)),
        leading: IconButton(
          icon: const Icon(Icons.arrow_back, color: Colors.white),
          onPressed: () {
            _resetAllKeyboards();
            Navigator.pushNamed(context, '/inventory');
          },
        ),
        actions: [
          IconButton(
            icon: const Icon(Icons.home, color: Colors.white),
            onPressed: () {
              _resetAllKeyboards();
              Navigator.pushNamed(context, '/home');
            },
          ),
        ],
        backgroundColor: const Color(0xFF008363),
      ),
      // 核心修改1：允许页面根据键盘高度调整
      resizeToAvoidBottomInset: true,
      body: Stack(
        children: [
          Positioned(
            top: 0,
            left: 0,
            right: 0,
            bottom: _bottomButtonHeight,
            child: GestureDetector(
              onTap: _resetAllKeyboards,
              behavior: HitTestBehavior.translucent,
              // 核心修改2：添加动态底部padding，预留键盘空间
              child: SingleChildScrollView(
                padding: EdgeInsets.only(
                  top: 16,
                  left: 32,
                  right: 32,
                  bottom: bottomInset + 20, // 键盘高度+20px间距，避免输入框贴键盘
                ),
                child: Column(
                  children: [
                    // 【核心：页面最上方添加Items列表】
                    _buildItemsList(),
                    
                    // 原有输入框区域（顺序不变）
                    _buildLabelInputRow(
                      label: 'Location:',
                      isRequired: true,
                      errorKey: 'location',
                      fieldType: 'location',
                    ),
                    const SizedBox(height: 20),
                    _buildLabelInputRow(
                      label: 'Item:',
                      isRequired: true,
                      errorKey: 'item',
                      fieldType: 'item',
                    ),
                    const SizedBox(height: 20),
                    _buildLabelInputRow(
                      label: 'Move Qty:',
                      isRequired: true,
                      errorKey: 'move quantity',
                      fieldType: 'quantity',
                      suffixWidget: currentQuantity != null
                          ? Text(
                              ' / $currentQuantity',
                              style: TextStyle(fontSize: 13 * _fontScale),
                            )
                          : null,
                    ),
                    const SizedBox(height: 20),
                    _buildLabelInputRow(
                      label: 'Dest Loc:',
                      isRequired: true,
                      errorKey: 'dest loc',
                      fieldType: 'destLoc',
                    ),
                    const SizedBox(height: 20),
                    Row(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        SizedBox(
                          width: 120,
                          child: Padding(
                            padding: const EdgeInsets.only(top: 8),
                            child: Text(
                              'Notes:',
                              style: TextStyle(
                                fontWeight: FontWeight.bold,
                                fontSize: 13 * _fontScale,
                              ),
                            ),
                          ),
                        ),
                        const SizedBox(width: 16),
                        Expanded(
                          child: TextField(
                            focusNode: _notesFocusNode,
                            controller: _notesController,
                            maxLines: 6,
                            decoration: const InputDecoration(
                              hintText: 'Note...',
                              border: OutlineInputBorder(),
                              contentPadding: EdgeInsets.all(10),
                            ),
                            style: TextStyle(fontSize: 13 * _fontScale),
                            onTap: _resetAllKeyboards,
                            onTapOutside: (event) => _notesFocusNode.unfocus(),
                          ),
                        ),
                      ],
                    ),
                    const SizedBox(height: 20),
                  ],
                ),
              ),
            ),
          ),
          // 底部Submit按钮（保留原逻辑）
          Positioned(
            bottom: 0,
            left: 0,
            right: 0,
            child: Container(
              padding: const EdgeInsets.all(24),
              color: Theme.of(context).scaffoldBackgroundColor,
              child: ElevatedButton(
                onPressed: _submitForm,
                style: ElevatedButton.styleFrom(
                  backgroundColor: const Color(0xFF008363),
                  padding: const EdgeInsets.symmetric(vertical: 16),
                  shape: RoundedRectangleBorder(
                    borderRadius: BorderRadius.circular(8),
                  ),
                ),
                child: Text(
                  'Submit',
                  style: TextStyle(
                    fontSize: 16 * _fontScale,
                    fontWeight: FontWeight.bold,
                    color: Colors.white
                  ),
                ),
              ),
            ),
          ),
        ],
      ),
    );
  }
}